<template>
  <div class="mod-config">
    <el-steps :active="activeStep" finish-status="success" align-center>
      <el-step title="基本信息"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="销售属性"></el-step>
      <el-step title="SKU信息"></el-step>
      <el-step title="保存完成"></el-step>
    </el-steps>

    <!-- 步骤一:基本信息 -->
    <el-form v-show="activeStep === 0" :model="baseForm" :rules="baseRules" ref="baseForm" label-width="120px">
      <el-form-item label="分类" prop="categoryId">
        <!-- <el-input v-model="dataForm.categoryId" placeholder="所属末级分类ID"></el-input> -->
        <category-cascader ref="categoryCascader" :categoryId="baseForm.categoryId" :catelogPath.sync="catelogPath"
          @getCategoryPath="getCategoryPath"></category-cascader>
        <!-- <category-cascader></category-cascader> -->
      </el-form-item>
      <el-form-item label="商品标题" prop="title">
        <el-input v-model="baseForm.title" placeholder="商品标题（含关键属性）"></el-input>
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input v-model="baseForm.description" placeholder="商品描述"></el-input>
      </el-form-item>
      <el-form-item label="主图" prop="mainImage">
        <!-- <el-upload class="upload-demo" ref="upload" action="http://localhost:88/api/oss/upload" :show-file-list="true"
          :on-change="fileChange" :file-list="fileList" accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG"
          :on-success="handle_success" list-type="picture" :auto-upload="true">
          <el-button>选择文件</el-button>
        </el-upload> -->
        <singleUpload v-model="baseForm.mainImage"></singleUpload>
      </el-form-item>
      <el-form-item label="基础定价" prop="basePrice">
        <el-input type="number" v-model.number="baseForm.basePrice" placeholder="基础定价（单位：元）"></el-input>
      </el-form-item>

      <el-form-item label="商品banner" prop="bannerImgs">
        <multiUpload v-model="baseForm.bannerImgs" />
      </el-form-item>

      <el-form-item label="商品介绍" prop="descImgs">
        <multiUpload v-model="baseForm.descImgs" />
      </el-form-item>

      <el-form-item label="商品状态" prop="status">
        <el-select v-model="baseForm.status" placeholder="请选择">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>



      <el-form-item>
        <el-button type="primary" @click="nextStep('baseForm')">下一步，填写商品属性</el-button>
      </el-form-item>
    </el-form>


    <!-- 步骤二:商品属性 -->
    <div v-show="activeStep === 1">
      <el-form :model="attrForm" ref="attrForm" label-width="120px">
        <el-table :data="attrForm.attrs" border style="width: 100%">
          <el-table-column label="属性名" prop="name">
            <template slot-scope="scope">
              <el-input v-model="scope.row.name" placeholder="请输入属性名"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="属性值" prop="value">
            <template slot-scope="scope">
              <el-input v-model="scope.row.value" placeholder="请输入属性值"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <!-- <el-button type="text" size="small" @click="editAttr(scope.$index)">编辑</el-button> -->
              <el-button type="text" size="small" @click="deleteAttr(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item>
          <el-button @click="addAttribute">添加属性</el-button>
          <el-button @click="prevStep">上一步，选择商品基本信息</el-button>
          <el-button type="primary" @click="nextStep('attrForm')">下一步，填写销售属性</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 步骤三:销售属性 -->
    <div v-show="activeStep === 2">
      <el-form :model="saleAttrForm" ref="saleAttrForm" label-width="120px">
        <el-table :data="saleAttrForm.attrs" border style="width: 100%">
          <el-table-column label="销售属性名" prop="name">
            <template slot-scope="scope">
              <el-input v-model="scope.row.name" placeholder="请输入销售属性名"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="销售属性值" prop="values">
            <template slot-scope="scope">
              <el-tag :key="tag" v-for="tag in scope.row.values" closable :disable-transitions="false"
                @close="handleClose(tag, scope.row)" style="margin-right: 10px;">
                {{ tag }}
              </el-tag>
              <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)">
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ 添加值</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="deleteSaleAttr(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item>
          <el-button @click="addSaleAttr">添加销售属性</el-button>
          <el-button @click="prevStep">上一步，填写商品属性</el-button>
          <el-button type="primary" @click="nextStep('saleAttrForm')">下一步，设置SKU信息</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 步骤四:SKU信息 -->
    <div v-show="activeStep === 3">
      <el-table :data="skuList" border>
        <el-table-column v-for="attr in saleAttrForm.attrs" :key="attr.name" :label="attr.name" :prop="attr.name">
        </el-table-column>
        <el-table-column label="售价">
          <template slot-scope="scope">
            <el-input v-model="scope.row.price" type="number"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="库存">
          <template slot-scope="scope">
            <el-input v-model="scope.row.stock" type="number"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div class="button-group">
        <el-button @click="prevStep">上一步，设置销售属性</el-button>
        <el-button type="primary" @click="nextStep('skuForm')">下一步，完成</el-button>
      </div>
    </div>

    <!-- 步骤五:完成 -->
    <div v-show="activeStep === 4" class="success-info">
      <i class="el-icon-success"></i>
      <h2>商品添加成功!</h2>
      <div class="button-group">
        <el-button @click="prevStep">上一步，设置SKU信息</el-button>
        <el-button type="success" @click="finish">完成</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import CategoryCascader from "../common/category-cascader.vue";
import MultiUpload from "../common/upload/multiUpload.vue";
import singleUpload from "../common/upload/singleUpload.vue";
export default {
  components: { CategoryCascader, MultiUpload, singleUpload },
  data() {
    return {
      activeStep: 1,
      catelogPath: [],

      baseForm: {
        categoryId: '',
        title: '',
        description: '',
        mainImage: '',
        basePrice: null,
        status: 1,
        // viewCount: '',
        // createdAt: '',
        // updatedAt: '',
        // 轮播图图片集合
        bannerImgs: [],
        // 详情图图片集合
        descImgs: [],

      },
      attrForm: {
        attrs: [] // 存储商品属性
      },
      newAttr: { // 用于存储新添加的属性
        name: '',
        value: ''
      },

      statusOptions: [{
        value: 1,
        label: '上架'
      }, {
        value: 0,
        label: '下架'
      }],
      baseRules: {
        categoryId: [
          { required: true, message: '所属末级分类ID不能为空', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '商品标题（含关键属性）不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '商品描述不能为空', trigger: 'blur' }
        ],
        mainImage: [
          { required: true, message: '主图URL地址不能为空', trigger: 'blur' }
        ],
        basePrice: [
          { required: true, message: '基础定价（单位：元）请输入合理价格', trigger: 'blur', validator: this.checkPositiveNumber }
        ],
        status: [
          { required: true, message: '商品状态不能为空', trigger: 'blur' }
        ],
        // viewCount: [
        //   { required: true, message: '累计浏览量不能为空', trigger: 'blur' }
        // ],
        bannerImgs: [
          { required: true, message: '商品banner不能为空', trigger: 'blur', },
        ],
        descImgs: [
          { required: true, message: '商品介绍图片不能为空', trigger: 'blur', },
        ],
        // updatedAt: [
        //   { required: true, message: '最后修改时间不能为空', trigger: 'blur' }
        // ]
      },
      categoryOptions: [
        {
          value: '1',
          label: '手机',
          children: [
            {
              value: '1-1',
              label: '手机通讯'
            },
            {
              value: '1-2',
              label: '手机配件'
            }
          ]
        }
      ],
      brandOptions: [{
        value: '1',
        label: '华为'
      }, {
        value: '2',
        label: '小米'
      }, {
        value: '3',
        label: '苹果'
      }, {
        value: '4',
        label: '三星'
      }, {
        value: '5',
        label: '联想'
      }, {
        value: '6',
        label: '魅族'
      }
      ],
      attrForm: {
        attrs: []
      },
      saleAttrForm: {
        attrs: []
      },
      skuList: []
    }
  },
  methods: {
    // 表单验证规则数字大于0
    checkPositiveNumber(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入一个数字'));
      } else {
        // 尝试将输入的值转换为浮点数
        const num = parseFloat(value);
        if (isNaN(num)) {
          callback(new Error('请输入一个有效的数字'));
        } else if (num <= 0) {
          callback(new Error('请输入一个大于0的数字'));
        } else {
          callback();
        }
      }
    },

    // 获取分类路径
    getCategoryPath(paths) {
      console.log("子组件传递的选中分类数据", paths);

      this.baseForm.categoryId = paths[paths.length - 1]
    },

    // 添加属性
    addAttribute() {
      this.attrForm.attrs.push({ name: '', value: '' });
    },

    // 编辑属性（这里假设编辑功能为更新属性，实际上可以弹出模态框进行编辑）
    editAttr(index) {
      // 这里可以添加弹出模态框进行编辑的逻辑
      console.log('编辑属性', index);
    },

    // 删除属性
    deleteAttr(index) {
      this.attrForm.attrs.splice(index, 1);
    },

    // 添加销售属性
    addSaleAttr() {
      this.saleAttrForm.attrs.push({
        name: '',
        values: [],
        inputVisible: false,
        inputValue: ''
      });
    },

    // 删除销售属性
    deleteSaleAttr(index) {
      this.saleAttrForm.attrs.splice(index, 1);
    },

    // 显示输入框
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // 处理输入确认
    handleInputConfirm(row) {
      let inputValue = row.inputValue;
      if (inputValue && row.values.indexOf(inputValue) === -1) {
        row.values.push(inputValue);
      }
      row.inputVisible = false;
      row.inputValue = '';
    },

    // 删除标签
    handleClose(tag, row) {
      row.values.splice(row.values.indexOf(tag), 1);
    },

    // 下一步
    nextStep(formName) {
      console.log("attrForm", this.attrForm.attrs);

      if (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.activeStep++
          } else {
            return false
          }
        })
      } else {
        this.activeStep++
      }
    },
    // 上一步
    prevStep() {
      this.activeStep--
    },
    // 完成
    finish() {
      this.$confirm('确认提交商品信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 调用保存接口
        this.$message({
          type: 'success',
          message: '商品添加成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消提交'
        })
      })
    },
    // 获取分类数据
    getCategoryData() {
      // TODO: 调用接口获取分类数据
    },
    // 获取品牌数据
    getBrandData() {
      // TODO: 调用接口获取品牌数据
    }
  },

  created() {
    this.getCategoryData()
    this.getBrandData()
  }
}
</script>

<style scoped>
.el-form-item>>>.el-input__inner {
  width: 300px;
  /* 根据需要调整宽度 */
}


.mod-config {
  padding: 20px;
}

.el-steps {
  margin-bottom: 40px;
}

.button-group {
  margin-top: 20px;
  text-align: center;
}

.success-info {
  text-align: center;
  padding: 40px 0;
}

.success-info i {
  font-size: 60px;
  color: #67C23A;
}

.success-info h2 {
  margin-top: 20px;
  color: #67C23A;
}

.el-form-item {
  margin-bottom: 22px;
}
</style>
